<template>
  <main class="common-content flex">
    <div class="person-left">
      <el-empty v-if="!treeData.length" />
      <template v-else>
        全部（{{ treeTotal }}道）
        <el-tree
          ref="treeRef"
          :data="treeData"
          style="max-width: 100%"
          @node-click="onNodeClick"
          node-key="id"
          highlight-current
          :default-checked-keys="activeKnow"
        >
          <template #default="{ data }">
            <div
              class="topic-title text-ellipsis"
              :class="activeKnow.includes(data.id) && 'topic-title-active'"
              :title="data.name"
            >
              {{ data.name }}&nbsp;({{ data.count }})道
            </div>
          </template>
        </el-tree>
      </template>
    </div>
    <div class="person-right">
      <div class="select-tool flex">
        <el-select
          v-model="search.questionType"
          placeholder="请选择题型"
          style="width: 240px"
          clearable
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="2"
          multiple
        >
          <el-option
            v-for="item in questionTypeOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <div class="right-rate">
          <p class="tip">得分率</p>
          <div class="input-box">
            <el-input-number
              placeholder="最低"
              :controls="false"
              :min="0"
              :max="100"
              v-model="search.low_rate"
            ></el-input-number>
            <span class="separator">—</span>
            <el-input-number
              placeholder="最高"
              :controls="false"
              :min="0"
              :max="100"
              v-model="search.high_rate"
            ></el-input-number>
          </div>
        </div>

        <el-select
          v-model="search.optionType"
          placeholder="请选择来源"
          style="width: 240px"
          clearable
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="2"
          multiple
        >
          <el-option
            v-for="item in optionOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>

      <div class="desc">
        共找到符合条件错题： <span class="text">{{ pageInfo.total }}</span
        >道 &nbsp;&nbsp;&nbsp;&nbsp; 本页共
        <span class="text">{{ questionList.length }}</span>
        道题目 &nbsp;&nbsp;&nbsp;
        <el-button
          text
          type="primary"
          @click="onAddBasket"
          :disabled="!questionList.length"
          >本页全选</el-button
        >
      </div>

      <el-empty v-if="!questionList.length" />
      <AssignTopic
        v-for="(question, index) in questionList"
        :key="index"
        :index="index + 1"
        :topic-data="question.question"
      />
      <el-pagination
        v-if="pageInfo.total"
        class="flex-end"
        layout="prev, pager, next"
        :total="pageInfo.total"
        v-model:current-page="pageInfo.pageIndex"
        @change="getWrongTargetInfo"
      />
    </div>
  </main>
</template>

<script setup>
import { ref, watchEffect, watch } from 'vue'
import {
  getQuestionCount,
  getQuestionType,
  getWrongTarget
} from '@/apis/assignment/index'
import { useAuthStore, useTaskStore } from '@/stores'
import { storeToRefs } from 'pinia'
import dayjs from 'dayjs'
import AssignTopic from '../components/AssignTopic.vue'
import { debounce } from '@/utils/debounce'

const props = defineProps({
  currentClass: {
    type: Array,
    default: () => [0, null]
  },
  stageId: Number,
  subjectId: Number,
  startTime: Object,
  endTime: Object,
  teacherId: String
})

const { nowGlobalStageId, nowGlobalSubjectId } = storeToRefs(useAuthStore())
const taskStore = useTaskStore()

const pageInfo = ref({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})
const questionList = ref([])
const questionTypeOption = ref([]) // 题型选项
const optionOption = ref([
  {
    label: '作业',
    value: 1
  },
  {
    label: '阅卷',
    value: 2
  },
  {
    label: '测验',
    value: 3
  },
  {
    label: '自习',
    value: 4
  },
  {
    label: '拍照录入',
    value: 20
  }
])
const search = ref({
  low_rate: 0,
  high_rate: 100,
  questionType: [],
  optionType: optionOption.value.map(item => item.value)
})

const getIds = (tree, result) => {
  for (let i = 0; i < tree.length; i++) {
    result.push(tree[i].id)
    if (tree[i].children) {
      getIds(tree[i].children, result)
    }
  }
  return result
}

const activeKnow = ref([])
const treeTotal = ref(0)
const treeData = ref([])
const treeRef = ref()
const onNodeClick = param => {
  resetData()
  activeKnow.value = getIds([param], [])
}

const resetData = () => {
  pageInfo.value = {
    pageIndex: 1,
    pageSize: 10,
    total: 0
  }
}

// 获取树状结构
const getQuestionCountInfo = async () => {
  if (!props.currentClass) return
  const res = await getQuestionCount({
    grade_id: props.currentClass[3],
    class_type: props.currentClass[2],
    class_id: props.currentClass[1],
    subject_id: props.subjectId,
    start_time: props.startTime
      ? dayjs(props.startTime).startOf('day').unix()
      : null,
    end_time: props.endTime ? dayjs(props.endTime).endOf('day').unix() : null,
    universal: 1
  })

  treeData.value = res.data?.data || []
  treeTotal.value = res.data?.total
  activeKnow.value = getIds(treeData.value, [])
}

// 知识图谱题目列表
const getWrongTargetInfo = async () => {
  if (!props.currentClass) return
  pageInfo.value.total = 0
  questionList.value = []
  const res = await getWrongTarget({
    class_type: props.currentClass[2],
    class_id: props.currentClass[1],
    subject_id: props.subjectId,
    category: search.value.questionType,
    order_by: 1,
    start_time: props.startTime
      ? dayjs(props.startTime).startOf('day').unix()
      : null,
    end_time: props.endTime ? dayjs(props.endTime).endOf('day').unix() : null,
    page: pageInfo.value.pageIndex,
    size: pageInfo.value.pageSize,
    knowledge_ids: activeKnow.value ? activeKnow.value : [],
    score_rate_interval: {
      min: search.value.low_rate || 0,
      max: search.value.high_rate || 100
    },
    origin_type: search.value.optionType,
    universal: 1
  })
  questionList.value = res.data.data || []
  pageInfo.value.total = res.data.total
}

// 获取题型
const getQuestionTypeInfo = async () => {
  const res = await getQuestionType({
    subject_id: nowGlobalSubjectId.value,
    stage_id: nowGlobalStageId.value
  })
  questionTypeOption.value = res.data.map(item => ({
    value: item.data.id,
    label: item.data.name
  }))
  // search.value.questionType = questionTypeOption.value.map(item => item.value)
}

// 题目数据加入选题篮中
const onAddBasket = () => {
  let list = questionList.value.map(item => ({
    topic_id: item.question.id,
    topic_type: item.question.type,
    is_similar: 0,
    relation_id: 0,
    question_detail: item.question,
    source: item.question.source,
    subject_id: item.question.subject
  }))
  taskStore.setTaskList(list, true)
}
watch(
  [() => search, activeKnow, () => props.currentClass],
  () => {
    debounce(() => {
      getWrongTargetInfo()
    }, 500)
  },
  {
    deep: true
  }
)

watchEffect(() => {
  getQuestionCountInfo()
})

watch(
  [nowGlobalStageId, nowGlobalSubjectId],
  () => {
    getQuestionTypeInfo()
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<style lang="less" scoped>
.common-content {
  margin-top: 20px;
  gap: 20px;
  align-items: self-start;
  overflow: hidden;
  height: calc(100vh - 160px);
  background-color: unset;
  .person-left {
    height: 100%;
    width: 400px;
    background-color: #fff;
    padding: 10px 10px 10px 20px;
    box-sizing: border-box;
    gap: 20px;
    overflow: auto;
    .tab-list {
      gap: 30px;
      .tab-item {
        color: #72757e;
      }
      .tab-item-active {
        color: #333333;
        font-weight: bold;
        font-size: 18px;
      }
    }
    .task-item {
      margin-bottom: 4px;
      line-height: 2.6;
      padding: 0 10px;
      border-radius: 10px;
      &:hover {
        background-color: #f7f9ff;
        color: #1a70e8;
        cursor: pointer;
      }
      .task-name {
        max-width: 80%;
      }
    }
    .task-item-active {
      background-color: #f7f9ff;
      color: #1a70e8;
    }

    :deep(.el-tree-node__content) {
      height: unset;
      line-height: 2.2;
      font-size: 16px;
      color: #000;
    }
    :deep(
        .el-tree--highlight-current
          .el-tree-node.is-current
          > .el-tree-node__content
      ) {
      background-color: #f7f9ff;
      color: #1a70e8;
    }
    .left-content {
      flex: 1;
      overflow-y: auto;
      .topic-title {
        width: 80%;
      }

      .topic-title-active {
      }
    }
  }
  .person-right {
    height: 100%;
    box-sizing: border-box;

    padding: 20px;
    flex: 1;
    background-color: #fff;
    overflow-y: auto;
    .select-tool {
      gap: 20px;
      .right-rate {
        display: flex;
        align-items: center;
        border: 1px solid #b7b8bb;
        height: 30px;

        * {
          font-size: 14px;
        }

        .tip {
          padding: 0 10px;
          font-size: 14px;
          color: #333333;
          width: fit-content;
          white-space: nowrap;
          border-right: 1px solid #b7b8bb;
          height: 100%;
          line-height: 30px;
        }

        .separator {
          color: #b7b8bb;
        }

        .input-box {
          .el-input-number {
            width: 100px;
            height: 28px;

            :deep(.el-input__wrapper) {
              border-radius: 0;
              // border: 1px solid #b7b8bb;
              border-left: unset;
              border-right: unset;
              box-shadow: none;
            }
          }
        }
      }
    }
    .desc {
      margin: 20px 0;
      .text {
        color: @theme-color;
      }
    }
  }
}
</style>
